﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Longtop.Web.WebSite.Models;
using System.ComponentModel;
using Longtop.Web.WebSite.Account;
using Longtop.Web.WebSite.Filters;
using Discuz.Toolkit;
using Longtop.Web.SaleWeb.Admin.Helper;
using Castle.ActiveRecord;
namespace Longtop.Web.WebSite.Admin.Controllers {

    [HandleError]
    public class AccountController : ControllerBase {





        // This constructor is used by the MVC framework to instantiate the controller using
        // the default forms authentication and membership providers.
        public AccountController()
            : this(null, null) {
        }

        // This constructor is not used by the MVC framework but is instead provided for ease
        // of unit testing this type. See the comments in AccountModels.cs for more information.
        public AccountController(IFormsAuthenticationService formsService, IMembershipService membershipService) {
            FormsService = formsService ?? new FormsAuthenticationService();
            MembershipService = membershipService ?? new AccountMembershipService();
        }

        public IFormsAuthenticationService FormsService {
            get;
            private set;
        }

        public IMembershipService MembershipService {
            get;
            private set;
        }

        protected override void Initialize(RequestContext requestContext) {
            if (requestContext.HttpContext.User.Identity is WindowsIdentity) {
                throw new InvalidOperationException("Windows authentication is not supported.");
            }
            else {
                base.Initialize(requestContext);
            }
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext) {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            base.OnActionExecuting(filterContext);
        }

        //public ActionResult Index([DefaultValue(1)] int pageIndex) {
        //    var model = new Account.IndexModel();
        //    int total;
        //    var users = Membership.GetAllUsers(pageIndex - 1, model.PageSize, out  total);
        //    var arr = (MembershipUser[])Array.CreateInstance(typeof(MembershipUser), users.Count);
        //    users.CopyTo(arr, 0);
        //    model.PagedList = new Longtop.Web.Helpers.PagedList<MembershipUser>(arr.ToList(), pageIndex, model.PageSize);
        //    model.PagedList.TotalCount = total;
        //    return View(model);
        //}
        [Description("修改密码")]
        public ActionResult ChangePassword() {
            return View(new ChangePasswordModel());
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model) {
            if (ModelState.IsValid) {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) {
                    Discuz.Toolkit.DiscuzSession ds = ConformityHandler.InitDiscuzSession();
                    int DntUid = ds.GetUserID(User.Identity.Name);
                    Discuz.Forum.Users.UpdateUserPassword(DntUid, model.NewPassword, true);
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [IgnoreAuthorizeAttrobite]
        public ActionResult ChangePasswordSuccess() {
            return View(new ChangePasswordModel());
        }
        [IgnoreAuthorizeAttrobite]
        public ActionResult LogOff() {
            FormsService.SignOut();
            Discuz.Toolkit.DiscuzSession ds = ConformityHandler.InitDiscuzSession();
            ds.Logout("");
            return RedirectToAction("Index", "Home");
        }
        [IgnoreAuthorizeAttrobite]
        public ActionResult LogOn() {
            return View();
        }



        [IgnoreAuthorizeAttrobite]
        [HttpPost]
        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public ActionResult LogOn(LogOnModel model, bool rememberMe, string returnUrl) {
            if (ModelState.IsValid) {
                if (MembershipService.ValidateUser(model.UserName, model.Password)) {
                    FormsService.SignIn(model.UserName, rememberMe);

                    DiscuzSession ds = ConformityHandler.InitDiscuzSession();
                    int DntUid = ds.GetUserID(model.UserName);
                    ds.Login(DntUid, model.Password, false, 100, "");

                    if (!String.IsNullOrEmpty(returnUrl)) {
                        return Redirect(returnUrl);
                    }
                    else {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult Register() {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model) {
            if (ModelState.IsValid) {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success) {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public MembershipCreateStatus Create(RegisterModel model, ModelStateDictionary ms) {

            MembershipCreateStatus createStatus = MembershipCreateStatus.UserRejected;
            if (ModelState.IsValid) {
                // Attempt to register the user
                createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success) {
                    //之间为DNT的整合代码
                    try {
                        Discuz.Toolkit.DiscuzSession ds = ConformityHandler.InitDiscuzSession();
                        ds.Register(model.UserName, model.Password, model.Email, false);
                    }
                    catch (Discuz.Toolkit.DiscuzException d) {
                        createStatus = MembershipCreateStatus.ProviderError;
                        Membership.DeleteUser(model.UserName);
                        ms.AddModelError("", "bbs:" + d.ErrorMessage);
                        if (d.ErrorCode == 109) {

                        }
                    }
                    catch (Exception ex) {
                        createStatus = MembershipCreateStatus.ProviderError;
                        Membership.DeleteUser(model.UserName);
                        ms.AddModelError("", "bbs:" + ex.Message);
                    }
                    //FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    //return RedirectToAction("Index", "Home");
                }
                else {
                    ms.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return createStatus;
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus) {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes.
            switch (createStatus) {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

    }
}
